<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /*
        then方法-异步及其多次调用
        1.定义实例属性
        2.保存回调函数
        3.调用成功回调函数
        4.调用失败回调函数
        */
        const PENDING = 'pending'
        const FULFILLED = 'fulfilled'
        const REJECTED = 'rejected'
        class HMPromise {
            //状态与原因
            state = PENDING
            result = undefined
            //实例属性
            #handlers = []// [{onFulfilled, onRejected}....]
            //构造函数
            constructor(executor) {
                //改状态， pending -> fulfilled
                //记录原因 
                const resolve = (result) => {
                    if (this.state === PENDING) {
                        this.state = FULFILLED
                        this.result = result
                        this.#handlers.forEach(handler => {
                            handler.onFulfilled(this.result)
                        })
                    }
                }
                //改状态， pending -> rejected
                const reject = (result) => {
                    if (this.state === PENDING) {
                        this.state = REJECTED
                        this.result = result
                        this.#handlers.forEach(handler => {
                            handler.onRejected(this.result)
                        })
                    }
                }
                executor(resolve, reject)
            }
            //添加实例方法then
            //2.参数判断
            //2.1成功，//2.2失败回调
            then(onFulfilled, onRejected) {
                onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x
                onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }

                if (this.state === FULFILLED) {
                    onFulfilled(this.result)
                } else if (this.state === REJECTED) {
                    onRejected(this.result)
                } else if (this.state === PENDING) {
                    this.#handlers.push({
                        onFulfilled,
                        onRejected
                    })
                }
            }
        }



        const p = new HMPromise((resolve, reject) => {
            console.log('执行器函数被调用')
            setTimeout(() => {
                resolve('success')
            }, 1000)
            // reject('fail')
        })

        p.then(res => {
            console.log('成功', res)
        }, err => {
            console.log('失败', err)
        })

        p.then(res => {
            console.log('成功', res)
        }, err => {
            console.log('失败', err)
        })

        p.then(res => {
            console.log('成功', res)
        }, err => {
            console.log('失败', err)
        })
    </script>
</body>

</html>